package com.waiting.rocket.controller;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
public class MyController {


    @Autowired
    RocketMQTemplate rocketMQTemplate;

    Jedis jedis = new Jedis("127.0.0.1", 6379);

    String redisKey = "lock";

    @GetMapping("/sell")
    public Map sell() {

        jedis.watch(redisKey);
        String redisValue = jedis.get(redisKey);
        int valInteger = Integer.valueOf(redisValue);
        String userInfo = UUID.randomUUID().toString();

        // 沒有秒完
        if (valInteger < 20) {
            Transaction tx = jedis.multi();
            tx.incr(redisKey);
            List list = tx.exec();
            // 秒成功 失敗返回空list而不是空
            if (list != null && list.size() > 0) {
                System.out.println("使用者：" + userInfo + "，秒殺成功！當前成功人數：" + (valInteger + 1));
            }
            // 版本變化，被別人搶了。
            else {
                System.out.println("使用者：" + userInfo + "，秒殺失敗");
            }
        }
        // 秒完了
        else {
            System.out.println("已經有20人秒殺成功，秒殺結束");
        }


        System.out.println("===== 秒殺開始 ======");

        rocketMQTemplate.syncSend("sell", userInfo);

        return null;
    }


}
